import { createSlice } from '@reduxjs/toolkit'

// 定义WebSocket切片
const websocketSlice = createSlice({
    name: 'websocket',
    initialState: {
        socket: null, // 初始状态为null
        isConnected: false // 是否连接状态
    },
    reducers: {
        // 初始化WebSocket实例
        initSocket(state, action) {
            state.socket = action.payload // 设置WebSocket实例
            state.isConnected = true // 设置连接状态为已连接
        },
        // 关闭WebSocket实例
        closeSocket(state) {
            if (state.socket) {
                state.socket.close() // 关闭WebSocket实例
            }
            state.socket = null // 清空WebSocket实例
            state.isConnected = false // 设置连接状态为未连接
        },
        // 其他可能的WebSocket相关状态更新，如错误处理等
    }
})

// 导出action creators
export const { initSocket, closeSocket } = websocketSlice.actions

// 导出reducer
export default websocketSlice.reducer